package com.fg.cloud.wechar.controller.account;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONArray;
import com.fg.cloud.common.PageUtils;
import com.fg.cloud.common.StatusCode;
import com.fg.cloud.common.finals.AgencyBill;
import com.fg.cloud.common.finals.UserType;
import com.fg.cloud.common.quantity.ResultType;
import com.fg.cloud.common.validate.LongUtils;
import com.fg.cloud.manager.entry.agency.AgencyBillEntity;
import com.fg.cloud.manager.entry.agency.vo.AgencyBillVo;
import com.fg.cloud.manager.entry.order.OrderPaymentEntity;
import com.fg.cloud.manager.service.agency.AgencyBillService;
import com.fg.cloud.wechar.controller.BaseWeCharController;

/**
 * Description:经销商手机端 流水controller
 * 
 * @author shaoqiping
 * @date 2017年8月21日下午2:31:13
 */
@Controller
@RequestMapping("/wecharBill")
public class WecharBillController extends BaseWeCharController {
	@Autowired
	AgencyBillService billService;

	/**
	 * Description:新增订单流水
	 * 
	 * @param request
	 * @param response
	 * @param billEntity
	 * @author shaoqiping
	 * @date 2017年8月25日上午11:01:27
	 */
	@RequiresRoles(UserType.AGENCY)
	@RequestMapping(value = "/addOrderFlow", method = { RequestMethod.POST })
	@ResponseBody
	public void insertOrderFlow(HttpServletRequest request, HttpServletResponse response, AgencyBillEntity billEntity,
			int mark) {
		try {
			if (billEntity == null || LongUtils.isEmpty(billEntity.getOrderId())) {
				doResult(response, false, StatusCode.LACKVALUE, null, "请选择要付款的订单");
				return;
			}
			if(mark==0){
				doResult(response, false, StatusCode.LACKVALUE, null, "请选择支付方式");
				return;
			}
			if(billEntity.getAmount()==null){
				doResult(response, false, StatusCode.LACKVALUE, null, "请选择填写交易金额");
				return;
			}
			billEntity.setFacId(getCurrentAgencyUser().getFacId());
			billEntity.setAgeId(getCurrentAgencyUser().getAgeId());
			billEntity.setTransTime(new Date());
			boolean temp = getCurrentAgencyUser().getAgencySetup().getReceivablesFlag() > 0;
			boolean flag = false;
			if (mark>0) {
				flag = billService.insertSelective(billEntity, temp);
			} else {
				flag = billService.insertDouble(billEntity, temp);
			}
			if (flag) {
				doResult(response, true, StatusCode.SAVESUCCESS, null, "交易成功");
			} else {
				doResult(response, false, StatusCode.SAVEERROR, null, "交易失败");
			}
		} catch (Exception e) {
			e.printStackTrace();
			doResult(response, false, StatusCode.EXCEPTIONERROR, null, e.getMessage());
		}
	}


	/**
	 * Description:新增充值流水
	 * 
	 * @param request
	 * @param response
	 * @param billEntity
	 * @author shaoqiping
	 * @date 2017年8月25日上午8:48:10
	 */
	@RequiresRoles(UserType.AGENCY)
	@RequestMapping(value = "/addAccountFlow", method = { RequestMethod.POST })
	@ResponseBody
	public void insertAccountFlow(HttpServletRequest request, HttpServletResponse response,
			AgencyBillEntity billEntity) {
		try {
			if (billEntity == null || billEntity.getAmount() == null || billEntity.getTransInfo() == null) {
				doResult(response, false, StatusCode.LACKVALUE, null, "请填写必要信息");
				return;
			}
			if (billEntity.getTransInfo() < 1 || billEntity.getTransInfo() > 4) {
				doResult(response, false, StatusCode.LACKVALUE, null, "请选择支付方式");
				return;
			}
			billEntity.setFacId(getCurrentAgencyUser().getFacId());
			billEntity.setAgeId(getCurrentAgencyUser().getAgeId());
			billEntity.setTransTime(new Date());
			boolean temp = getCurrentAgencyUser().getAgencySetup().getReceivablesFlag() > 0;
			if (billEntity.getTransInfo() == AgencyBill.REFUND) {
				billEntity.setConfirmTime(new Date());
				billEntity.setConfirmAmount(billEntity.getAmount());
				billEntity.setStatus(AgencyBill.STATUS);
			} else {
				if (!temp) {
					if (billEntity.getTransMode() <= AgencyBill.CONFIRM) {
						billEntity.setConfirmTime(new Date());
						billEntity.setConfirmAmount(billEntity.getAmount());
						billEntity.setStatus(AgencyBill.STATUS);
					}
				}
			}
			boolean flag = billService.insert(billEntity,temp);
			if (flag) {
				if (billEntity.getTransInfo() == AgencyBill.AMOUNT_ADD) {
					doResult(response, true, StatusCode.SAVESUCCESS, null, "充值成功");
				} else if (billEntity.getTransInfo() == AgencyBill.REPAYMENT) {
					doResult(response, true, StatusCode.SAVESUCCESS, null, "还款成功");
				} else {
					doResult(response, true, StatusCode.SAVESUCCESS, null, "退款成功");
				}
			} else {
				if (billEntity.getTransInfo() == AgencyBill.AMOUNT_ADD) {
					doResult(response, false, StatusCode.SAVEERROR, null, "充值失败");
				} else if (billEntity.getTransInfo() == AgencyBill.REPAYMENT) {
					doResult(response, false, StatusCode.SAVEERROR, null, "还款失败");
				} else {
					doResult(response, false, StatusCode.SAVEERROR, null, "退款失败");
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			doResult(response, false, StatusCode.EXCEPTIONERROR, null, e.getMessage());
		}
	}
	/**
	 * Description:查询未完成付款的订单
	 * 
	 * @param request
	 * @param response
	 * @author shaoqiping
	 * @date 2017年9月8日下午3:36:20
	 */
	@RequiresRoles(UserType.AGENCY)
	@RequestMapping(value = "/findUnfinished", method = { RequestMethod.POST, RequestMethod.GET })
	@ResponseBody
	public void findUnfinished(HttpServletRequest request, HttpServletResponse response) {
		try {
			doResult(response, true, StatusCode.FINDSUCCESS,
					billService.findUnfinished(getCurrentAgencyUser().getFacId(), getCurrentAgencyUser().getAgeId()),
					ResultType.FIND_SUCCESS);
		} catch (Exception e) {
			e.printStackTrace();
			doResult(response, false, StatusCode.EXCEPTIONERROR, null, e.getMessage());
		}
	}

	/**
	 * Description:选择未完成订单进行付款
	 * 
	 * @param request
	 * @param response
	 * @param ids
	 * @param amount
	 * @author shaoqiping
	 * @date 2017年9月8日下午4:19:57
	 */
	@RequiresRoles(UserType.AGENCY)
	@RequestMapping(value = "/orderPayment", method = { RequestMethod.POST, RequestMethod.GET })
	@ResponseBody
	public void orderPayment(HttpServletRequest request, HttpServletResponse response, String keyValue,
			AgencyBillEntity billEntity) {
		try {
			if (billEntity == null || billEntity.getAmount() == null) {
				doResult(response, false, StatusCode.LACKVALUE, null, "请填写必要信息");
				return;
			}
			if (keyValue == null || StringUtils.isEmpty(keyValue)) {
				doResult(response, false, StatusCode.LACKVALUE, null, "请选择相应订单");
				return;
			}
			billEntity.setFacId(getCurrentAgencyUser().getFacId());
			billEntity.setAgeId(getCurrentAgencyUser().getAgeId());
			billEntity.setTransTime(new Date());
			boolean temp = getCurrentAgencyUser().getAgencySetup().getReceivablesFlag() > 0;
			boolean confirm=false;
			if (billEntity.getTransInfo() == AgencyBill.REFUND) {
				billEntity.setConfirmTime(new Date());
				billEntity.setConfirmAmount(billEntity.getAmount());
				billEntity.setStatus(AgencyBill.STATUS);
			} else {
				if (!temp) {
					if (billEntity.getTransMode() <= AgencyBill.CONFIRM) {
						billEntity.setConfirmTime(new Date());
						billEntity.setConfirmAmount(billEntity.getAmount());
						billEntity.setStatus(AgencyBill.STATUS);
						confirm=true;
					}
				}
			}
			billEntity.setTransInfo(AgencyBill.REPAYMENT);
			List<OrderPaymentEntity> payments = JSONArray.parseArray(keyValue, OrderPaymentEntity.class);
			BigDecimal template = BigDecimal.ZERO;
			for (OrderPaymentEntity orderPaymentEntity : payments) {
				template = template.add(orderPaymentEntity.getNeedPay());
			}
			if (billEntity.getAmount().compareTo(template) > 0) {
				doResult(response, false, StatusCode.SAVEERROR, null, "还款金额不能大于订单总金额");
				return;
			}
			boolean flag = billService.orderPayment(billEntity,confirm);
			if (flag) {
				doResult(response, true, StatusCode.SAVESUCCESS, null, "还款成功");
			} else {
				doResult(response, false, StatusCode.SAVEERROR, null, "还款失败");
			}
		} catch (Exception e) {
			e.printStackTrace();
			doResult(response, false, StatusCode.EXCEPTIONERROR, null, e.getMessage());
		}
	}

	/**
	 * Description:删除未确认的流水
	 * 
	 * @param request
	 * @param response
	 * @param id
	 * @author shaoqiping
	 * @date 2017年8月24日下午5:38:12
	 */
	@RequiresRoles(UserType.AGENCY)
	@RequestMapping(value = "/deleteUnconfirmed", method = { RequestMethod.POST, RequestMethod.GET })
	@ResponseBody
	public void deleteUnconfirmed(HttpServletRequest request, HttpServletResponse response, Long id) {
		try {
			if (id == null || LongUtils.isEmpty(id)) {
				doResult(response, false, StatusCode.LACKVALUE, null, ResultType.CHOOSE_INFO);
				return;
			}
			boolean flag = billService.deleteUnconfirmed(id, getCurrentAgencyUser().getAgeId());
			if (flag) {
				doResult(response, true, StatusCode.REMOVESUCCESS, null, ResultType.REMOVE_SUCCESS);
			} else {
				doResult(response, false, StatusCode.REMOVEERROR, null, ResultType.REMOVE_FAULT);
			}
		} catch (Exception e) {
			e.printStackTrace();
			doResult(response, false, StatusCode.EXCEPTIONERROR, null, e.getMessage());
		}

	}
	
	/**
	  * Description:查询订单付款详情
	  * @param request
	  * @param response
	  * @param orderId
	  * @author shaoqiping
	  * @date 2017年9月14日下午3:06:33
	*/
	@RequiresRoles(UserType.AGENCY)
	@RequestMapping(value = "/findOrderAmount", method = { RequestMethod.POST, RequestMethod.GET })
	@ResponseBody
	public void findOrderAmount(HttpServletRequest request, HttpServletResponse response,Long orderId){
		try {
			if(orderId==null||LongUtils.isEmpty(orderId)){
				doResult(response, false, StatusCode.LACKVALUE, null, "请选择相应订单");
				return;
			}
			doResult(response, true, StatusCode.FINDSUCCESS, billService.findOrderPayment(orderId), ResultType.FIND_SUCCESS);
		} catch (Exception e) {
			e.printStackTrace();
			doResult(response, false, StatusCode.EXCEPTIONERROR, null, e.getMessage());
		}
	}
	/**
	 * Description:条件分页查询所有流水
	 * 
	 * @param request
	 * @param response
	 * @param page
	 * @param rows
	 * @param sort
	 * @param order
	 * @param filterText
	 * @param startTime
	 * @param endTime
	 * @param entity
	 * @author shaoqiping
	 * @date 2017年8月21日下午2:13:42
	 */
	@RequiresRoles(UserType.AGENCY)
	@RequestMapping(value = "/findList", method = { RequestMethod.POST, RequestMethod.GET })
	@ResponseBody
	public void findList(HttpServletRequest request, HttpServletResponse response, Integer page, Integer rows,
			String sort, String order, String filterText, String startTime, String endTime, AgencyBillVo entity) {
		try {
			// page默认为1 rows默认为10
			if (page == null || page <= 0) {
				page = 1;
			}
			if (rows == null || rows <= 0) {
				rows = 10;
			}
			PageUtils<AgencyBillVo> pageinfo = new PageUtils<AgencyBillVo>(page, rows, sort, order);
			Map<String, Object> condition = pageinfo.getCondition();
			condition.put("filterText", filterText);
			condition.put("facId", getCurrentAgencyUser().getFacId());
			condition.put("ageId", getCurrentAgencyUser().getAgeId());
			condition.put("startTime", startTime);
			condition.put("endTime", endTime);
			condition.put("status", entity.getStatus());
			condition.put("transInfo", entity.getTransInfo());
			condition.put("flag", AgencyBill.AGE);
			pageinfo.setCondition(condition);

			billService.findList(pageinfo);
			doResult(response, true, StatusCode.FINDSUCCESS, pageinfo, ResultType.FIND_SUCCESS);
		} catch (Exception e) {
			e.printStackTrace();
			doResult(response, false, StatusCode.EXCEPTIONERROR, null, e.getMessage());
		}
	}

	/**
	 * Description:条件分页查询所有支付记录
	 * 
	 * @param request
	 * @param response
	 * @param page
	 * @param rows
	 * @param sort
	 * @param order
	 * @param filterText
	 * @param startTime
	 * @param endTime
	 * @param entity
	 * @author shaoqiping
	 * @date 2017年9月4日下午5:46:58
	 */
	@RequiresRoles(UserType.AGENCY)
	@RequestMapping(value = "/findPayment", method = { RequestMethod.POST, RequestMethod.GET })
	@ResponseBody
	public void findPayment(HttpServletRequest request, HttpServletResponse response, Integer page, Integer rows,
			String sort, String order, String filterText, String startTime, String endTime, AgencyBillVo entity) {
		try {
			// page默认为1 rows默认为10
			if (page == null || page <= 0) {
				page = 1;
			}
			if (rows == null || rows <= 0) {
				rows = 10;
			}
			PageUtils<AgencyBillVo> pageinfo = new PageUtils<AgencyBillVo>(page, rows, sort, order);
			Map<String, Object> condition = pageinfo.getCondition();
			condition.put("filterText", filterText);
			condition.put("facId", getCurrentAgencyUser().getFacId());
			condition.put("ageId", getCurrentAgencyUser().getAgeId());
			condition.put("startTime", startTime);
			condition.put("endTime", endTime);
			condition.put("status", entity.getStatus());
			condition.put("transInfo", entity.getTransInfo());
			condition.put("flag3", !AgencyBill.AGE);
			pageinfo.setCondition(condition);

			doResult(response, true, StatusCode.FINDSUCCESS, billService.findListWeChat(pageinfo), ResultType.FIND_SUCCESS);
		} catch (Exception e) {
			e.printStackTrace();
			doResult(response, false, StatusCode.EXCEPTIONERROR, null, e.getMessage());
		}
	}
}
